<template>
    <div>
        <!-- 面包屑导航栏区域-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片内容区域-->
        <el-card>
            <!-- 分为24格 搜索框区域-->
            <el-row :gutter="20">
                <!-- 搜索框-->
                <el-col :span="8">
                    <el-input placeholder="用户名" class="input-with-select" v-model="queryInfo.query" clearable
                              @clear="queryUserList">
                        <el-button slot="append" icon="el-icon-search" @click="queryUserList"></el-button>
                    </el-input>
                </el-col>
                <!-- 按钮-->
                <el-col :span="4">
                    <el-button type="success" @click="dialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 表格数据显示区域-->
            <el-table
                    :data="listUser"
                    border
                    style="width: 100%">
                <el-table-column type="index"/>
                <el-table-column prop="username" label="用户名" width="180"/>
                <el-table-column prop="email" label="邮箱" width="200"/>
                <el-table-column prop="mobile" label="电话" width="180"/>
                <el-table-column prop="role_name" label="角色" width="180"/>
                <!-- 后端返回的是布尔值, 需要使用作用域插槽来渲染开关-->
                <el-table-column label="状态" width="180">
                    <template v-slot="scope">
                        <el-switch v-model="scope.row.mg_state" @change="changeState(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="190">
                    <template v-slot="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showUser(scope.row.id)"/>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"/>
                        <el-tooltip class="item" effect="dark" content="分配角色" placement="right-start"
                                    :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini"
                                       @click="showRole(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页数据显示区域-->
            <div class="block">
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="queryInfo.pagenum"
                        :page-sizes="[5, 10, 15]"
                        :page-size="queryInfo.pagesize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                </el-pagination>
            </div>
        </el-card>
        <!-- 添加用户表单区域-->
        <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%">
            <!-- 表单主体-->
            <el-form ref="addUserRef" :model="addUser" :rules="addUserRules" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addUser.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addUser.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addUser.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="addUser.mobile"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部按钮-->
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveUser">确 定</el-button>
               </span>
        </el-dialog>
        <!-- 更新用户信息区域 -->
        <el-dialog
                title="编辑用户信息"
                :visible.sync="dialogEdit"
                width="30%">
            <el-form ref="updateUserRef" :model="updateUser" :rules="updateUserRules" label-width="80px">
                <el-form-item label="用户名">
                    <el-input v-model="updateUser.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="updateUser.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="updateUser.mobile"></el-input>
                </el-form-item>
            </el-form>
            <!-- 更新用户信息底部按钮-->
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogEdit = false">取 消</el-button>
                <el-button type="primary" @click="renewalUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 为用户分配角色区域-->
        <el-dialog
                title="分配角色"
                :visible.sync="roleIsVisible"
                width="30%"
                @close="clearInstance"
        >
            <div>
                <p>当前用户名: {{roleUser.username}}</p>
                <p>当前用户拥有的角色: {{roleUser.role_name}}</p>
                <p>分配角色
                    <el-select label="角色" v-model="selectedRoleId" clearable placeholder="请选择" @clean="">
                        <el-option
                                v-for="item in rolesList"
                                :key="item.value"
                                :label="item.roleName"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
            <el-button @click="roleIsVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveRole">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        name: "user.vue",
        data() {
            // 验证邮箱的规则
            var checkEmail = (rule, value, cb) => {
                // 验证邮箱的正则表达式
                const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

                if (regEmail.test(value)) {
                    // 合法的邮箱
                    return cb()
                }

                cb(new Error('请输入合法的邮箱'))
            }

            // 验证手机号的规则
            var checkMobile = (rule, value, cb) => {
                // 验证手机号的正则表达式
                const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

                if (regMobile.test(value)) {
                    return cb()
                }

                cb(new Error('请输入合法的手机号'))
            }
            return {
                // 用户查询条件
                queryInfo: {
                    // 查询条件
                    query: '',
                    // 当前页码
                    pagenum: 1,
                    // 每页多少条数据
                    pagesize: 5
                },
                // 分配角色时,保存角色id
                selectedRoleId: '',
                listUser: [],
                roleUser: {},
                rolesList: [],
                // 总几记录数
                total: 0,
                updateUser: {},
                // 是否显示添加用户对话框
                dialogVisible: false,
                dialogEdit: false,
                roleIsVisible: false,
                addUser: {
                    username: '',
                    email: '',
                    mobile: '',
                    role_name: '',

                },
                addUserRules: {
                    username: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                        {
                            min: 3,
                            max: 10,
                            message: '用户名的长度在3~10个字符之间',
                            trigger: 'blur'
                        }
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {
                            min: 6,
                            max: 15,
                            message: '用户名的长度在6~15个字符之间',
                            trigger: 'blur'
                        }
                    ],
                    email: [
                        {required: true, message: '请输入邮箱', trigger: 'blur'},
                        {validator: checkEmail, trigger: 'blur'}
                    ],
                    mobile: [
                        {required: true, message: '请输入手机号', trigger: 'blur'},
                        {validator: checkMobile, trigger: 'blur'}
                    ]
                },
                updateUserRules: {
                    email: [
                        {required: true, message: '请输入邮箱', trigger: 'blur'},
                        {validator: checkEmail, trigger: 'blur'}
                    ],
                    mobile: [
                        {required: true, message: '请输入手机号', trigger: 'blur'},
                        {validator: checkMobile, trigger: 'blur'}
                    ]
                }
            }
        },
        // 生命周期函数 data和methods加载完成的时候
        // 查询用户列表
        created() {
            this.queryUserList();
        },
        methods: {
            queryUserList() {
                this.$http.get('/users', {params: this.queryInfo})
                    .then(res => {
                        res = res.data;
                        if (res.meta.status !== 200) {
                            return this.$message.error('获取用户列表失败！')
                        }
                        this.listUser = res.data.users;
                        this.total = res.data.total;
                    }).catch(err => {
                })
            },
            // 每页显示多少条数据
            handleSizeChange(size) {
                this.queryInfo.pagesize = size;
                this.queryUserList();

            },
            handleCurrentChange(pagenum) {
                this.queryInfo.pagenum = pagenum;
                this.queryUserList();
            },
            async changeState(userInfo) {

                const {data: res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`);
                if (res.meta.status !== 200) {
                    userInfo.mg_state = !userInfo.mg_state
                    return this.$message.error('更新用户状态失败！')
                } else {
                    this.$message.closeAll()
                    this.$message.success('更新用户状态成功')
                }

            },
            // 点击确定按钮,先校验数据
            // 通过后发送请求
            saveUser() {
                this.$refs.addUserRef.validate(async valid => {
                    if (!valid) return;
                    const {data: res} = await this.$http.post('users', this.addUser);
                    this.$message.closeAll()
                    if (res.meta.status !== 201) return this.$message.error("添加失败");

                    this.$message.success("添加成功");
                    this.queryUserList();
                    this.dialogVisible = false;

                })
            },
            // 点击编辑按钮,展示用户信息
            async showUser(id) {

                const {data: res} = await this.$http.get(`users/${id}`)

                this.dialogEdit = true;
                if (res.meta.status !== 200) return this.$message.error("获取用户信息失败")

                this.updateUser = res.data;
            },
            // 用户点击确定发送请求修改用户信息
            renewalUser() {
                this.$refs.updateUserRef.validate(async valid => {
                    if (!valid) return;
                    let id = this.updateUser.id;
                    const {data: res} = await this.$http.put(`users/${id}`, this.updateUser);
                    this.$message.closeAll()
                    if (res.meta.status !== 200) return this.$message.error("更新用户失败");

                    this.$message.success("更新成功");
                    this.queryUserList();
                    this.dialogEdit = false;
                })
            },
            async deleteUser(id) {
                const res = await this.$confirm('是否删除该用户?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err);
                // 用户点击确认返回的是 confirm
                // 用户点击取消 cancel
                // console.log(res);
                this.$message.closeAll();
                if (res !== 'confirm') return this.$message.info("取消删除");
                const {data: r} = await this.$http.delete(`users/${id}`)
                if (r.meta.status !== 200) return this.$message('删除失败');
                this.$message.success('删除成功');
                this.queryUserList();
            },
            // 点击分配角色
            async showRole(role) {

                this.roleUser = role;
                const {data: res} = await this.$http.get(`roles`);
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
                this.rolesList = res.data;
                this.roleIsVisible = true;
            },
            // 用户点击保存 分配角色
            async saveRole() {
                if (!this.selectedRoleId){
                    this.roleIsVisible = false
                    return this.$message.success("保存成功!");
                }
                const {data: res} = await this.$http.put(`users/${this.roleUser.id}/role`, {rid: this.selectedRoleId});
                if(res.meta.status !== 200)return this.$message.error(res.meta.msg);
                this.queryUserList();
                this.roleIsVisible = false
            },
            // 关闭分配角色对话框
            // 重置对象
            clearInstance(){
                this.selectedRoleId = '';
                this.rolesList = [];
            }
        },
        watch: {
            // 监听添加用户的窗口是否关闭
            // 如果关闭了,则清空表单
            dialogVisible(val) {
                if (!this.dialogVisible) {
                    this.$refs.addUserRef.resetFields();
                }
            }
        }
    }
</script>

<style scoped>

</style>